<template>
  <view class="multipleAccount">
    <view class="head">
      <image src="../../static/images/BackIcon.png" mode="scaleToFill" @click="goBack" />
    </view>
    <view class="content">
      <view class="title">选择登录账户</view>
      <view class="contetn-container">
        <view class="phone">手机号码: {{ phone }}</view>
        <view
          class="box"
          v-for="(item, index) in accountList"
          :key="item.userId || item.username"  
          @click="handleSelect(item)"
        >
          <!-- 动态显示用户名首字母 -->
          <view class="circle">{{ item.username.charAt(0).toUpperCase() }}</view>
          <view class="accountName">{{ item.username }}</view>
          <!-- 显示选中状态 -->
          <myCheckbox :modelValue="selectedAccount === item.username" />
        </view>
        <button class="login" @click="confirmSelection">确认</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import myCheckbox from '@/components/checkbox.vue'
import { ref } from 'vue'
import { Local } from "@/utils/storage"
import { onLoad, onShow } from '@dcloudio/uni-app'
import { apiLoginUserId } from '@/api/login'  // 假设这个接口用于切换用户登录

// 当前手机号
const phone = ref('')

// 当前选中的用户名（用于 UI 显示）
const selectedAccount = ref('')

// 当前选中的用户 userId（真正要传给后端的）
const selectedUserId = ref(0)

// 用户账户列表
const accountList = ref([])

// 接收跳转参数：手机号
onLoad((e) => {
  if (e?.phone) {
    console.log('接收到手机号:', e.phone)
    phone.value = e.phone
  }
})

// 页面显示时更新账户列表
onShow(() => {
  const userInfo = Local.get('userInfo')
  if (Array.isArray(userInfo)) {
    accountList.value = userInfo
    console.log('账户列表:', accountList.value)
  } else {
    accountList.value = []
  }
})

// 处理选择：单选逻辑
const handleSelect = (item) => {
  // 保存选中的 username 和 userId
  selectedAccount.value = item.username
  selectedUserId.value = item.userId // 根据实际字段名调整
}

// 确认选择：提交到后端
const confirmSelection = async () => {
  if (!selectedUserId.value) {
    uni.showToast({
      title: '请选择一个账户',
      icon: 'none',
      duration: 2000
    })
    return
  }

  uni.showLoading({ title: '登录中...' })

  try {
    const res = await apiLoginUserId({ userId: selectedUserId.value })

    if (res.code === 200 && res.data) {
      // 登录成功，保存当前用户信息或 token
      Local.set('token', res.data.token)
      Local.set('userItem', res.data.user)

      uni.showToast({
        title: '登录成功',
        icon: 'none',
      })

      // 可选：跳转到首页或返回上一页
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/index/index' })
      }, 500)
    } else {
      throw new Error(res.message || '登录失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '网络异常',
      icon: 'none',
      duration: 2000
    })
    console.error('登录失败:', error)
  } finally {
    uni.hideLoading()
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.multipleAccount {
  background-color: rgb(106, 106, 235);
  width: 100vw;
  height: 100vh;
  position: relative;
  .head {
    position: absolute;
    top: 40rpx;
    left: 40rpx;
    image {
      width: 100rpx;
      height: 100rpx;
    } 
  }
  .content {
    position: absolute;
    top: 155rpx;
    width: 87%;
    left: 50rpx;
    height: 85%; // 控制最大宽度
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
    background-color: #A0C0FE;
    border-radius: 40rpx;
    box-sizing: border-box;
    .title {
      text-align: center;
      padding: 20rpx 0;
      height: 80rpx;
      background-color: #d5d8ff;
      border-top-left-radius: 40rpx;
      border-top-right-radius: 40rpx;
      line-height: 80rpx;
      color: #1a195a;
    }
    .contetn-container {
      padding: 0 40rpx;
      .phone {
        margin-top: 30rpx;
        color: #fff;
        margin-left: 20rpx;
        font-size: 33rpx;
      }
      .box {
        width: 100%;
        height: 160rpx;
        background-color: #fff;
        border-radius: 40rpx;
        margin-top: 36rpx;
        display: flex;
        align-items: center;
        .circle {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          background: #8e9ea1;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 0 20rpx;
          font-weight: 527;
          font-size: 64rpx;
          color: #fff;
        }
        .accountName {
          font-size: 30rpx;
          width: 380rpx;
          text-align: left;
        }
      }
      .login { 
        margin-top: 70rpx;
        background-color: #5756B3;
        color: #fff;
        border-radius: 40rpx;
        height: 100rpx;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>